
 
   import 'package:flutter/material.dart';
import 'dart:convert';
  import 'package:http/http.dart' as http;

class DataPage extends StatefulWidget {
  DataPage({Key key}) : super(key: key);

  

  @override
  _DataPageState createState() => _DataPageState();
}

class _DataPageState extends State<DataPage> {

  String _msg;

  @override
  void initState(){
    super.initState();
    // Map userInfo = {
    // 'username': '李白',
    // 'age': 20,
    // };

    // var a = json.encode(userInfo); // 把Map类型数据转换成json字符串
    // print(userInfo is Map);
    // print(a is String);

    // String userInfo = '{"username":"李白", "age":"20"}';
    // Map u = json.decode(userInfo); // 把json字符串转换成Map类型
    // print(u['username']);

  }

  // 请求数据
  _getData() async{
    // https://jd.itying.com/api/httpGet
    var apiUrl = Uri.parse('https://jd.itying.com/api/httpGet');
    var response = await http.get(apiUrl);

    if(response.statusCode==200){
      print(json.decode(response.body));
    } else {
      print(response.statusCode);
    }

    // print('Response status: ${response.statusCode}');
    // print('Response body: ${response.body}');
    // print(response.body is String);
    // setState(() {
    //  this._msg = json.decode(response.body)['msg'];     
    // });

  }

  // 提交数据
  _postData() async{
    var apiUrl = Uri.parse('https://jd.itying.com/api/httpPost');
    var response = await http.post(apiUrl, body: {'username':'战三', 'age':'20' });
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
    print(response.body is String);

    setState(() {
     this._msg = json.decode(response.body)['msg'];     
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Demo'),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ElevatedButton(
                  onPressed: _getData,
                  child: Text('Get请求数据'),
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: _postData,
                  child: Text('post提交数据'),
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  child: Text('get请求数据，渲染数据'),
                  onPressed: (){
                    Navigator.pushNamed(context, '/http');
                  },
                ),
              ],
            ),
          ),
        ),
       );
  }
}